<script lang="ts" setup>
import type { StateType } from './types';
import { $t } from '@vben/locales';
import { computed } from 'vue';
import { useRoute } from 'vue-router';

import { Page,useVbenDrawer ,z} from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import Draggable from 'vuedraggable';
import { useTitle } from '@vueuse/core';
import {
  Card,
  message,
  Select,
  SelectOption,
  TabPane,
  Tabs,
  Input,
  Textarea
} from 'ant-design-vue';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
import { pinyin } from 'pinyin-pro';

import { useVbenForm } from '#/adapter/form';
import { getPage_news, postPage_news, putPage_news } from '#/api/portal/vechilebanner';
import { usePreferencesStore } from '#/store';
import Upload from "#/components/Upload";


const route = useRoute();

const { setTabTitle, closeCurrentTab } = useTabs();

const index: any = computed(() => {
  return route.params?.id ?? -1;
});
const router = useRouter();

const routeMeta = router.currentRoute.value.meta;
const routeTitle = 'banner';
const preferencesStore = usePreferencesStore();
const { title } = storeToRefs(preferencesStore);
const pageTitle =
  Number.parseInt(index.value, 10) === 0
    ? `新增${routeTitle}`
    : `No.${index.value} - 编辑${routeTitle}`;
setTabTitle(pageTitle);
useTitle(`${pageTitle} - ${title.value}`);

const disabled = ref(true);
const activeKey = ref('1');
const state: StateType = reactive({
  form: {
    post_title: '',
    post_alias: '',
    more: {
      thumbnail: '',
    },
    icon:[],
  },
  pageThemeFiles: [],
});
const id=ref();
const [Drawer, DrawerApi] = useVbenDrawer({
     
      async onConfirm() {
            await onSubmit();
            DrawerApi.close();
     },
    async onOpenChange(isOpen) {
        if (isOpen) {
        const modalData: any = await DrawerApi.getData();
        id.value = modalData.id;
        const data = modalData.bannerOptions;
        data.post = {
            id: data?.id ?? undefined,
            title: data?.title ?? '',
            content: data?.content ?? '',
            icon: data?.icon ?? [],

            images: data?.images ?? [],
            background: data?.background ?? [],
        };
          state.form = data.post;
          BasicFormApi.setValues({ ...state.form});
          const icon = data.post.icon;
          contentList.value = Array.isArray(icon) &&icon.length > 0 &&!(icon.length === 1 && icon[0] === '') ? JSON.parse(JSON.stringify(icon)) : contentList.value;
                
        }
    }
})






const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  submitButtonOptions:{
    show:false
  },
  resetButtonOptions: {
    show: false,
  },
  commonConfig: {
    // labelWidth: 200,
  },
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    },


    
    {
      component: 'Input',
      defaultValue: '',
      dependencies: {
        trigger: (values) => {
          disabled.value = !values.news_title;
          state.form.title = values.title;
          state.form.content = values.content;
          state.form.icon = values.icon;
          state.form.images = values.images;
          state.form.background = values.background;
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'id',
          'title',
          'content',
          'icon',
          'images',
          'background'
        ],
      },
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'title',
      label: $t('page.common.Title'),
       rules: z.string().max(30,'标题不能超过30'),
    },
 

    {
      component: 'Textarea',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'content',
      label: $t('page.common.Description'),
    },

    {
      component: 'Upload',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'images',
      label: $t('page.common.Model Images'),
    },
     {
      component: 'Upload',
      defaultValue: '',
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'background',
      label: $t('page.common.Background Image'),
    },
    {
      component: 'icon',
      defaultValue: [{title:'',images:[{'url':'','id':''}]}],
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'icon',
       label: `${routeTitle}`+$t('page.common.Icon'),
    },



  ],
});

async function onSubmit() {
     updateForm();
    const values: any = state.form;
    let response;
    values.car_model = id.value;
    DrawerApi.setData(values);
    message.success('操作成功');
   
}




const contentList = ref([
  { title: '', images: [{ url: '/upload/default/20250703/bfed90791eaeac65cc3d5ed094dab3a9.png', id: 639 }]},
  { title: '', images: [{ url: '/upload/default/20250703/d5c32642870d928e82e4613b7bf34ba2.png', id: 638 }]},
  { title: '', images: [{ url: '/upload/default/20250703/cbfebdb526acfc54c4175785cf41f78a.png', id: 637 }]},
  { title: '', images: [{ url: '/upload/default/20250703/f282d836d3948947263edb1c3b3bafd9.png', id: 636 }]},
  { title: '', images: [{ url: '/upload/default/20250703/a72197ad6bcf2da372dc88bd25274bb2.png', id: 635 }]}
]);


function onUpdateName(index, value) {

  contentList.value[index].title = value
  updateForm()
}

// 更新 content

function createContentItem() {
  return {
    title: '',
    images: [{ url: '', id: '' }],
    is_checked: false
  };
}

function addContentItem() {
  contentList.value.push(createContentItem());
  updateForm();
}
function removeContentItem(index) {
    if (contentList.value.length <= 1) {return;}
  contentList.value.splice(index, 1) // 删除指定下标的项
  updateForm()                       // 同步到表单
}


// 同步到表单字段
function updateForm() {
  state.form.icon = JSON.parse(JSON.stringify(contentList.value));
  //BasicFormApi.setFieldValue('icon', JSON.parse(JSON.stringify(contentList.value))) // 深拷贝同步表单

}


</script>

<template>
    <Drawer>
        <Page>
            <Card :title="routeTitle+' '+$t('page.common.Details')">
            <BasicForm>
                
                <template #icon>
                <div class="content_s">
                        <Card>
                        <Draggable v-model="contentList" item-key="id"  handle=".cursor-pointer" class="grid grid-cols-1 gap-6 tubiao">
                                <template #item="{ element, index }">
                                <div class="flex gap-4 items-start" style="marginc-top: 16px; padding: 16px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);    flex-direction: column;">
                                    <!-- 图片上传 -->
                                    <Upload
                                    list-type="picture-card"
                                    v-model="element.images"
                                    :tips="'尺寸:50x50px,size:100K以内'"
                                    style="flex-shrink: 0;"
                                    />

                                    <div class="flex flex-col gap-3 w-full">
                                    <!-- 标题输入 -->
                                    <Textarea
                                        v-model:value="element.title"
                                        :placeholder="$t('page.common.Please Enter')+' '+$t('page.common.Title')"
                                        class="w-full"
                                        minHeight="200"
                                        maxlength="250"
                                        @input="onUpdateName(index, element.title)"
                                    />

                                    <!-- 删除按钮 -->
                                    <div class="flex gap-6 justify-end items-center">
                                        <Button danger type="dashed" @click="removeContentItem(index)">{{$t('page.common.Delete')}}</Button>
                                        <Button type="dashed" @click="addContentItem">{{$t('page.common.Add')}}</Button>
                                        <Icon icon="ri:menu-2-line"  class="cursor-pointer"  title="点击拖动" />
                                    </div>
                                    </div>
                                </div>
                                </template>
                            </Draggable>
                            


                                
                        </Card>




                    

                    <div>
                        
                    
                    </div>
                </div>  
                
                
                </template>


            </BasicForm>
            </Card>
        </Page>
    </Drawer>
  
</template>


<style scoped>

 :deep(.ant-upload-list-item-container) {
     width: 50px !important;
      height: 50px !important;
  }

  :deep(.upload-init-me){
    width: 50px !important;
    height: 50px !important;
  }
  :deep(.tubiao .ant-upload-wrapper.ant-upload-picture-card-wrapper 
  .ant-upload-list.ant-upload-list-picture-card 
  .ant-upload-list-item-container) {
  background-color: red;
}
</style>